package com.chookss.home.audit.service;


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.base.Token;
import com.chookss.home.entity.ReimbursementDetailEntity;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//用章、离职、晋升公用一个
public class UploadSealService extends Service {
    //    private VODUploadClient uploader;
    private String secretToken;
    public static int NotificationId = 1;
    private ArrayList<ReimbursementDetailEntity.AnnexsBean.PictureInfoListBean> picList = new ArrayList<>();
    private ArrayList<ReimbursementDetailEntity.AnnexsBean.DatabaseBean> docunmentList = new ArrayList<>();
    private int picNum = 0, docunmentNum = 0;
    private ArrayList<ReimbursementDetailEntity> allList = new ArrayList<>();
    //专门设置这两个值以防止多个日志同时上传  第一个上传完立即上传，然后每次上传的都是列表最新的一个
    private ArrayList<Integer> statusList = new ArrayList<>();
    private boolean beginUpload = false;//上传中不得重新开始
    private boolean stopUpload = false;//默认正常上传  当true时切换账号中止上传

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //初始化短视频上传对象
        MyApp.uploadHolidayStatus = true;
        EventBus.getDefault().register(this);
        secretToken = Token.INSTANCE.getToken();
        registerBoradcastReceiver();
        initNotification();
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        ReimbursementDetailEntity reimbursementDetailEntity = (ReimbursementDetailEntity) intent.getSerializableExtra("reimbursementDetailEntity");
        int newCacheStatus = intent.getIntExtra("cacheStatus", 0);
        if (reimbursementDetailEntity != null) {
            allList.add(reimbursementDetailEntity);
            statusList.add(newCacheStatus);
            dealCacheData(newCacheStatus, reimbursementDetailEntity);
            setNewLogData();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void setNewLogData() {
        if (!beginUpload) {
            beginUpload = true;
            picList.clear();
            docunmentList.clear();
            picNum = 0;
            docunmentNum = 0;
            for (int i = 0; i < allList.get(0).getAnnexs().size(); i++) {
                picList.addAll(allList.get(0).getAnnexs().get(i).getPictureInfoList());
                docunmentList.addAll(allList.get(0).getAnnexs().get(i).getDatabase());
            }
            if (picList.size() == 0) {
                if (docunmentList.size() == 0) {
                    uploadData();
                } else {
                    uploadDocunment();
                }
            } else {
                uploadPic();
            }
        }
    }

    private void uploadPic() {
        if (picList.get(picNum).getPictureUrl().startsWith("http")) {
            picNum++;
            if (picNum >= picList.size()) {
                if (docunmentList.size() == 0) {
                    uploadData();
                } else {
                    uploadDocunment();
                }
            } else {
                uploadPic();
            }
        } else {
            if (stopUpload) {
                dealCacheData(2, null);
                stopSelf();
                return;
            }
            MyHttpRequest.uploadPicture(Urls.uploadPicture, this, "4", new File(picList.get(picNum).getPictureUrl()), new JsonCallback<String>() {
                @Override
                public void onSuccess(Response<String> response) {
                    JSONObject result = null;
                    JSONObject data = null;
                    try {
                        if (stopUpload) {
                            dealCacheData(2, null);
                            stopSelf();
                            return;
                        }
                        result = new JSONObject(response.body().toString());
                        if (result.getString("code").equals("200")) {
                            data = result.getJSONObject("data");
                            Message msg = handler.obtainMessage();
                            msg.arg1 = (picNum * 100) / (picList.size() + docunmentList.size());
                            handler.sendMessage(msg);
                            for (int i = 0; i < allList.get(0).getAnnexs().size(); i++) {
                                for (int j = 0; j < allList.get(0).getAnnexs().get(i).getPictureInfoList().size(); j++) {
                                    if (allList.get(0).getAnnexs().get(i).getPictureInfoList().get(j).getPictureUrl().equals(picList.get(picNum).getPictureUrl())) {
                                        allList.get(0).getAnnexs().get(i).getPictureInfoList().get(j).setPictureUrl(data.getString("originalUrl"));
                                    }
                                }
                            }

                            picNum++;
                            if (picNum >= picList.size()) {
                                if (docunmentList.size() == 0) {
                                    uploadData();
                                } else {
                                    uploadDocunment();
                                }
                            } else {
                                uploadPic();
                            }
                        } else {
                            dealCacheData(2, null);
                            if (result.getString("code").startsWith("400")) {
                                OkGoUtil.onErrorIntent(result.getString("code"), result.getString("msg"));
                            } else {
                                MyToast.show("图片上传失败，请稍后重试");
                            }
                            stopSelf();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        dealCacheData(2, null);
                        MyToast.show("图片上传失败，请稍后重试");
                        stopSelf();
                    }
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    dealCacheData(2, null);
                    MyToast.show("图片上传失败，请稍后重试");
                    stopSelf();
                }
            });
        }
    }

    private void uploadDocunment() {
        if (!Utils.isNull(docunmentList.get(docunmentNum).getDataCode())) {
            docunmentNum++;
            if (docunmentNum >= docunmentList.size()) {
                uploadData();
            } else {
                uploadDocunment();
            }
        } else {
            if (stopUpload) {
                dealCacheData(2, null);
                stopSelf();
                return;
            }
            MyHttpRequest.uploadDataFileNew(Urls.uploadDataFile, this, new File(docunmentList.get(docunmentNum).getDataPath()), new JsonCallback<String>() {
                @Override
                public void onSuccess(Response<String> response) {
                    JSONObject result = null;
                    try {
                        if (stopUpload) {
                            dealCacheData(2, null);
                            stopSelf();
                            return;
                        }
                        result = new JSONObject(response.body().toString());
                        if (result.getString("code").equals("200")) {
                            Message msg = handler.obtainMessage();
                            msg.arg1 = ((picNum + docunmentNum) * 100) / (picList.size() + docunmentList.size());
                            handler.sendMessage(msg);
                            for (int i = 0; i < allList.get(0).getAnnexs().size(); i++) {
                                for (int j = 0; j < allList.get(0).getAnnexs().get(i).getDatabase().size(); j++) {
                                    if (allList.get(0).getAnnexs().get(i).getDatabase().get(j).getDataPath().equals(docunmentList.get(docunmentNum).getDataPath())) {
                                        allList.get(0).getAnnexs().get(i).getDatabase().get(j).setDataCode(result.getString("data"));
                                    }
                                }
                            }

                            docunmentNum++;
                            if (docunmentNum >= docunmentList.size()) {
                                uploadData();
                            } else {
                                uploadDocunment();
                            }
                        } else {
                            dealCacheData(2, null);
                            if (result.getString("code").startsWith("400")) {
                                OkGoUtil.onErrorIntent(result.getString("code"), result.getString("msg"));
                            } else {
                                MyToast.show("资料上传失败，请稍后重试");
                            }
                            stopSelf();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        dealCacheData(2, null);
                        MyToast.show("资料上传失败，请稍后重试");
                        stopSelf();
                    }
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    dealCacheData(2, null);
                    MyToast.show("资料上传失败，请稍后重试");
                    stopSelf();
                }
            });
        }
    }

    private void uploadData() {
        Map<String, Object> map = new HashMap<>();
        map.put("type", allList.get(0).getType());
        map.put("baoixaoTypeCode", allList.get(0).getBaoixaoTypeCode());
        map.put("baoxiaoTypeCode", allList.get(0).getBaoixaoTypeCode());
        map.put("baoxiaoTypeName", allList.get(0).getBaoxiaoTypeName());
        map.put("baoixaoTypeName", allList.get(0).getBaoxiaoTypeName());
        map.put("employeeCode", allList.get(0).getEmployeeCode());
        map.put("employeeName", allList.get(0).getEmployeeName());
        map.put("orgCode", allList.get(0).getOrgCode());
        map.put("orgName", allList.get(0).getOrgName());
        if (!Utils.isNull(allList.get(0).getGroupCode())) {
            map.put("groupCode", allList.get(0).getGroupCode());
            map.put("groupName", allList.get(0).getGroupName());
        }

        List<Map<String, String>> list = new ArrayList<>();
        for (int i = 0; i < allList.get(0).getAnnexs().size(); i++) {
            Map<String, String> maps = new HashMap<>();
            String pictureUrl = "", fileUrl = "";
            maps.put("baoixaoTypeCode", allList.get(0).getBaoixaoTypeCode());
            maps.put("annexName", allList.get(0).getAnnexs().get(i).getAnnexName());
            for (int j = 0; j < allList.get(0).getAnnexs().get(i).getPictureInfoList().size(); j++) {
                String newUrl=allList.get(0).getAnnexs().get(i).getPictureInfoList().get(j).getPictureUrl().split("\\?")[0];
                if (j != 0) {
                    pictureUrl = pictureUrl + "," + newUrl;
                } else {
                    pictureUrl = pictureUrl + newUrl;
                }
            }
            for (int j = 0; j < allList.get(0).getAnnexs().get(i).getDatabase().size(); j++) {
                if (j != 0) {
                    fileUrl = fileUrl + "," + allList.get(0).getAnnexs().get(i).getDatabase().get(j).getDataCode();
                } else {
                    fileUrl = fileUrl + allList.get(0).getAnnexs().get(i).getDatabase().get(j).getDataCode();
                }
            }
            maps.put("fileUrl", fileUrl);
            maps.put("pictureUrl", pictureUrl);
            list.add(maps);
        }
        map.put("annexs", XJson.listToJsArrays(list));
        String url = "";
        if(allList.get(0).getType().equals("14")){
            //离职
            map.put("remark", allList.get(0).getRemark());
            if (Utils.isNull(allList.get(0).getWorkflowId())) {
                url = Urls.insertEmpLeaveInfo;
            } else {
                url = Urls.updateEmpLeaveInfo;
                map.put("leaveCode", allList.get(0).getLeaveCode());
                map.put("workflowId", allList.get(0).getWorkflowId());


            }
        }else if(allList.get(0).getType().equals("15")){
            //晋升
            map.put("baseSalary", allList.get(0).getBaseSalary());
            map.put("postSalary", allList.get(0).getPostSalary());
            map.put("workSalary", allList.get(0).getWorkSalary());
            map.put("oldBaseSalary", allList.get(0).getOldBaseSalary());
            map.put("oldPostSalary", allList.get(0).getOldPostSalary());
            map.put("oldWorkSalary", allList.get(0).getOldWorkSalary());
            map.put("addSalary", allList.get(0).getAddSalary());
            map.put("levelCode", allList.get(0).getLevelCode());
            map.put("levelName", allList.get(0).getLevelName());
            map.put("effTime", allList.get(0).getEffTime());
            map.put("remark", allList.get(0).getRemark());
            if (Utils.isNull(allList.get(0).getWorkflowId())) {
                url = Urls.insertEmpUpInfo;
            } else {
                url = Urls.updateEmpUpInfo;
                map.put("upCode", allList.get(0).getUpCode());
                map.put("workflowId", allList.get(0).getWorkflowId());
            }
        }else{
            //刻章
            map.put("useNum", allList.get(0).getUseNum());
            if (allList.get(0).getBaoxiaoTypeName().equals("刻章")) {
                map.put("useDetail", allList.get(0).getUseDetail());
            } else {
                map.put("remark", allList.get(0).getRemark());
                map.put("useTime", allList.get(0).getUseTime());
                map.put("outCd", allList.get(0).getOutCd());
            }
            if (Utils.isNull(allList.get(0).getUseCode())) {
                url = Urls.insertUseZhang;
            } else {
                url = Urls.updateUseZhang;
                map.put("useCode", allList.get(0).getUseCode());
                map.put("workflowId", allList.get(0).getWorkflowId());
            }
        }

        if (stopUpload) {
            dealCacheData(2, null);
            stopSelf();
            return;
        }
        MyHttpRequest.postRequestJson(url, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        dealCacheData(1, allList.get(0));
                        for (int i = 0; i < picList.size(); i++) {
                            FileUtilss.delFile(picList.get(i).getLocPictureUrl());
                        }
                        if (allList.size() > 1) {
                            allList.remove(0);
                            beginUpload = false;
                            setNewLogData();
                        } else {
                            EventBus.getDefault().post(new MyEvent("RefreshSealRecord"));
                            MyToast.show("提交成功");
                            stopSelf();
                        }
                    } else {
                        dealCacheData(2, null);
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                        stopSelf();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dealCacheData(2, null);
                    MyToast.show("提交失败，请稍后重试");
                    stopSelf();
                }

            }
        });
    }


    private NotificationManager mNManager;
    private Notification notification;

    private void initNotification() {
        //获得通知消息管理类对象
        mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Bitmap largeBitmap = GlideUtils.loadLogo(this);
        notification = new Notification(GlideUtils.loadLogoId(this), "带进条的提醒", System.currentTimeMillis());
//Android8.0以上必须添加 渠道 才能显示通知栏
        RemoteViews contentView = new RemoteViews(getApplication().getPackageName(), R.layout.vedio_upload);
        contentView.setProgressBar(R.id.progressbarUpload, 100, 0, false);
        contentView.setTextViewText(R.id.tvProcess, "已上传" + "0%");
        contentView.setImageViewResource(R.id.appdown_ivLogo, GlideUtils.loadLogoId(this));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //创建渠道
            String id = "vedio_upload_channel";
            String name = getResources().getString(R.string.app_name);
            NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
            mNManager.createNotificationChannel(mChannel);
            //设置图片,通知标题,发送时间,提示方式等属性
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, id);
            int PROGRESS_MAX = 100;
            int PROGRESS_CURRENT = 0;
            builder.setCustomContentView(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false)
                    .setAutoCancel(true);       //设置点击后取消Notification
            notification = builder.build();
//            startForeground(1, notification);

        } else {
            //设置图片,通知标题,发送时间,提示方式等属性
            Notification.Builder builder = new Notification.Builder(this);
            builder.setContent(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setAutoCancel(true);       //设置点击后取消Notification
            notification = builder.build();
        }
        mNManager.notify(NotificationId, notification);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            notification.contentView.setProgressBar(R.id.progressbarUpload, 100, msg.arg1,
                    false);
            notification.contentView.setTextViewText(R.id.tvProcess, "已上传"
                    + msg.arg1 + "%");
            mNManager.notify(NotificationId, notification);
            if (msg.arg1 == 100) {
                mNManager.cancel(NotificationId);
            }
            super.handleMessage(msg);
        }
    };

    private void dealCacheData(int type, ReimbursementDetailEntity data) {
        //0开始上传缓存本地备份1成功 2失败3重新上传
        if (type == 2) {
            for (int i = 0; i < allList.size(); i++) {
                if(allList.get(i).getType().equals("11")){
                    //用章
                    XJson.setReimbursementDetailEntityCache(this, type, "seal", allList.get(i));
                }else if(allList.get(i).getType().equals("14")){
                    //离职
                    XJson.setReimbursementDetailEntityCache(this, type,"resign",  allList.get(i));
                }else if(allList.get(i).getType().equals("15")){
                    //晋升
                    XJson.setReimbursementDetailEntityCache(this, type,"upgrade",  allList.get(i));
                }
            }
        } else {
            if(data.getType().equals("11")){
                //用章
                XJson.setReimbursementDetailEntityCache(this, type,"seal",  data);
            }else if(data.getType().equals("14")){
                //离职
                XJson.setReimbursementDetailEntityCache(this, type,"resign",  data);
            }else if(data.getType().equals("15")){
                //晋升
                XJson.setReimbursementDetailEntityCache(this, type,"upgrade",  data);
            }
        }

    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (context != null && intent != null && intent.getAction() != null) {

                if (action.equals(StaticClass.ACCOUNT_OUT)) {
                    //账号退出所有 上传数据全部当做失败处理
                    dealCacheData(2, null);
                    stopSelf();
                }
            }
        }

    };
    private boolean registTag = false;//判断重复注册

    private void registerBoradcastReceiver() {
        if (mBroadcastReceiver != null) {
            IntentFilter myIntentFilter = new IntentFilter();
            myIntentFilter.addAction(StaticClass.ACCOUNT_OUT);// 关闭
            //注册广播
            LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
            registTag = true;
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();

        } else {
            String msg = messageEvent.getMessage();
            if (!Utils.isNull(msg)) {
                if (msg.equals("Stop_File_Upload")) {
                    //中止上传任务
                    stopUpload = true;
                    MyApp.uploadRecordStatus = false;
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MyApp.uploadHolidayStatus = false;
        EventBus.getDefault().unregister(this);
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
        if (mNManager != null) {
            mNManager.cancel(NotificationId);
        }
    }
}